/*************************************************************************
	> File Name: udp_server.hpp
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/10/01 19:07
 ************************************************************************/

#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <queue>
#include <cerrno>
#include <cstdio>
#include <strings.h>
#include <unordered_map>
#include "log.hpp"

const int BUF_SIZE = 1024;
const int RES_SIZE = 1024;
const int KEY_SIZE = 1024;


class UdpServer
{
public:
    UdpServer (uint16_t port, std::string ip = ""):_port(port), _ip(ip)
    {}
    bool initServer()
    {
        if ((_sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
            logMessage(FATAL, "%d:%s", errno, strerror(errno));
            exit(2);
        }
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = _ip.empty() ? INADDR_ANY : inet_addr(_ip.c_str());
        if (bind(_sock, (struct sockaddr*)&local, sizeof local) < 0) {
            logMessage(FATAL, "%d:%s", errno, strerror(errno));
            exit(2);
        }
        logMessage(NORMAL, "init udp server done ... %s", strerror(errno));
        return true;
    }

    void start()
    {
        char buffer[BUF_SIZE];
        while (1) {
            memset(buffer, 0, sizeof buffer);
            struct sockaddr_in peer;
            bzero(&peer, sizeof peer);
            socklen_t len = sizeof peer;
            char result[RES_SIZE];
            char key[KEY_SIZE];
            std::string message;
            ssize_t s = recvfrom(_sock, buffer, sizeof buffer - 1, 0, (struct sockaddr*)&peer, &len);
            if (s > 0) {
                uint16_t cli_port = ntohs(peer.sin_port);
                std::string cli_ip = inet_ntoa(peer.sin_addr);
                snprintf(key, sizeof key, "%s:%u", cli_ip.c_str(), cli_port);
                logMessage(NORMAL, "key:%s", key);
                const auto it = _users.find(key);
                if (it == _users.end()) {
                    logMessage(NORMAL, "Add new user:%s", key);
                    _users.insert({key, peer});
                }
            }
            for (const auto &i : _users) {
                std::string sendMessage = key;
                sendMessage += "# ";
                sendMessage += buffer;
                logMessage(NORMAL, "push message to %s", i.first.c_str());
                sendto(_sock, sendMessage.c_str(), sendMessage.size(), 0, (struct sockaddr*)&(i.second), sizeof i.second);
            }
        }
    }
    virtual ~UdpServer ()
    {
        if (_sock >= 0) {
            close(_sock);
        }
    }

private:
    uint16_t _port;
    std::string _ip;
    int _sock;
    std::unordered_map<std::string, struct sockaddr_in> _users ;
    std::queue<std::string> _messageQueue;
};


